package top.lyc829.zzl_android.ui.travel.edit_travel;

import androidx.core.widget.NestedScrollView;
import androidx.lifecycle.ViewModelProvider;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.Image;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.base.XPageFragment;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xpage.utils.TitleBar;
import com.xuexiang.xui.utils.StatusBarUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Response;
import okhttp3.internal.Util;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.logic.bean.ActivityBean;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.bean.SubTravelBean;
import top.lyc829.zzl_android.logic.bean.TravelDetailBean;
import top.lyc829.zzl_android.logic.bean.TravelItemBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.GlideEngine;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.KeyBoardUtils;
import top.lyc829.zzl_android.logic.util.RichUtils;
import top.lyc829.zzl_android.logic.util.Url;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;
import top.lyc829.zzl_android.ui.custom_view.RichEditor;

import static com.google.android.material.tabs.TabLayout.MODE_SCROLLABLE;

@Page(name = "EditTravelFragment", anim = CoreAnim.none)
public class EditTravelFragment extends XPageFragment {

    Map<Integer, String> contentMap = new HashMap<>();

    TextView txtFinish, txtPublish, txtPreview;
    ImageView buttonRichUndo, buttonRichDo, buttonBold, buttonUnderline,
            buttonListUl, buttonListOl, buttonImage;
    RichEditor richEditor;
    EditText editName;
    NestedScrollView editTravelScroll;

    TabLayout tabLayout;

    private EditTravelViewModel mViewModel;

    MiniLoadingDialog mMiniLoadingDialog;

    @Override
    protected TitleBar initTitleBar() {
        return null;
    }

    public static EditTravelFragment newInstance() {
        return new EditTravelFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.edit_travel_fragment;
    }


    @Override
    protected void initViews() {

        mMiniLoadingDialog =  WidgetUtils.getMiniLoadingDialog(getContext());
        mMiniLoadingDialog.updateMessage("上传图片中");
        mMiniLoadingDialog.setCancelable(false);

        LinearLayout leoBar = findViewById(R.id.leoBar);
        StatusBarUtils.initStatusBarStyle(getActivity(), false, getResources().getColor(R.color.white, null));
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) leoBar.getLayoutParams();
        lp.setMargins(0, StatusBarUtils.getStatusBarHeight(getContext()), 0, 0);
        leoBar.setLayoutParams(lp);

        mViewModel = new ViewModelProvider(getActivity()).get(EditTravelViewModel.class);

        txtFinish = findViewById(R.id.txt_finish);
        txtPublish = findViewById(R.id.txt_publish);
        editName = findViewById(R.id.edit_name);
        richEditor = findViewById(R.id.rich_Editor);
        buttonRichUndo = findViewById(R.id.button_rich_undo);
        buttonRichDo = findViewById(R.id.button_rich_do);
        buttonBold = findViewById(R.id.button_bold);
        buttonUnderline = findViewById(R.id.button_underline);
        buttonListUl = findViewById(R.id.button_list_ul);
        buttonListOl = findViewById(R.id.button_list_ol);
        buttonImage = findViewById(R.id.button_image);
        txtPreview = findViewById(R.id.txt_preview);
        tabLayout = findViewById(R.id.edit_travel_tab);
        editTravelScroll = findViewById(R.id.edit_travel_scroll);

        Bundle arguments = getArguments();
        TravelDetailBean travelDetail = (TravelDetailBean) arguments.getSerializable("travel_detail");
        if (travelDetail != null) {
            editName.setText(travelDetail.getTitle());
            for (SubTravelBean item : travelDetail.getContent()) {
                contentMap.put(item.getActivityId(), item.getText());
            }
        }

        initEditor();
        clickListener();

        observer();


        if (travelDetail != null && !Utils.isStringEmpty(travelDetail.getTitle()) && travelDetail.getContent().size() > 0) {
            txtPublish.setSelected(true);
            txtPublish.setEnabled(true);
            txtPreview.setSelected(true);
            txtPreview.setEnabled(true);
        }

    }

    private void observer() {
        // 页面从长时间在后台重新进入前台时可能会丢失数据，依赖ViewModel恢复数据
        mViewModel.getTravelTitleLiveData().observe(getViewLifecycleOwner(), s -> {
            if (Utils.isStringEmpty(editName.getText().toString()) && !Utils.isStringEmpty(s)) {
                editName.setText(s);
            }
        });


        mViewModel.getActivitiesLiveData().observe(getViewLifecycleOwner(), activityBeans -> {
            if (activityBeans != null && activityBeans.size() > 0) {
                List<TravelItemBean> itemTravel = new ArrayList<>();
                for (int i = 0; i < activityBeans.size(); i++) {
                    tabLayout.addTab(tabLayout.newTab().setText("活动" + (i + 1)));
                    String text = "";
                    if (contentMap.containsKey(activityBeans.get(i).getId())) {
                        text = contentMap.get(activityBeans.get(i).getId());
//                        contentMap.remove(activityBeans.get(i).getId());
                    }
                    itemTravel.add(new TravelItemBean(activityBeans.get(i).getId(), text));
                }
                // 设置子游记的文本
                mViewModel.getItemTravelLiveData().setValue(itemTravel);
                richEditor.setHtml(itemTravel.get(0).getText());

                tabLayout.setTabMode(MODE_SCROLLABLE);
                tabLayout.clearOnTabSelectedListeners();
                // 因为数据只会改变一次，这么写也没关系
                tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                    @Override
                    public void onTabSelected(TabLayout.Tab tab) {
                        List<TravelItemBean> itemTravels = mViewModel.getItemTravelLiveData().getValue();
                        if (itemTravels != null) {
                            richEditor.setHtml(itemTravels.get(tab.getPosition()).getText());
                            richEditor.focusEditor();
                        }

                    }

                    @Override
                    public void onTabUnselected(TabLayout.Tab tab) {

                    }

                    @Override
                    public void onTabReselected(TabLayout.Tab tab) {

                    }
                });
            }

        });
    }

    @Override
    protected void initListeners() {

    }

    private void clickListener() {
        txtFinish.setOnClickListener(v -> popToBack());
        txtPublish.setOnClickListener(v -> {
            mViewModel.getTravelTitleLiveData().setValue(editName.getText().toString().trim());

            publishTravel(Utils.getUserId());
        });
        txtPreview.setOnClickListener(v -> {
            List<TravelItemBean> itemTravels = mViewModel.getItemTravelLiveData().getValue();
            int travelTextNumber = 0;
            if (itemTravels != null) {
                for (TravelItemBean travelItem : itemTravels) {
                    if (travelItem.getText() != null) {
                        travelTextNumber += travelItem.getText().length();
                    }
                }
                if (!Utils.isStringEmpty(editName.getText().toString())
                        && travelTextNumber > 0) {
                    openPage("PreviewTravelFragment");
                }
            }

        });

        //撤销
        buttonRichUndo.setOnClickListener(v -> richEditor.undo());
        // 反撤销
        buttonRichDo.setOnClickListener(v -> richEditor.redo());
        buttonBold.setOnClickListener(v -> {
            againEdit();
            //richEditor.setBold();
            richEditor.setHeading(3);
        });
        buttonUnderline.setOnClickListener(v -> {
            againEdit();
            richEditor.setUnderline();
        });
        buttonListUl.setOnClickListener(v -> {
            againEdit();
            richEditor.setBullets();
        });
        buttonListOl.setOnClickListener(v -> {
            againEdit();
            richEditor.setNumbers();
        });

        buttonImage.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(richEditor.getHtml())) {
                ArrayList<String> arrayList = RichUtils.returnImageUrlsFromHtml(richEditor.getHtml());
                if (arrayList != null && arrayList.size() >= 9) {
                    Utils.showToast("最多添加9张照片~");
                    return;
                }
            }

            KeyBoardUtils.closeKeybord(editName, getContext());

            PictureSelector.create(this)
                    .openGallery(PictureMimeType.ofImage())
                    .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                    .isMaxSelectEnabledMask(true)
                    .selectionMode(PictureConfig.SINGLE)
                    .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                    .isEnableCrop(true)
                    .showCropFrame(true)
                    .showCropGrid(true)
                    .hideBottomControls(false)
                    .isCompress(true)
                    .isAndroidQTransform(true)
                    .freeStyleCropEnabled(true)
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(List<LocalMedia> result) {
                            againEdit();

                            mMiniLoadingDialog.show();

                            File file = new File(result.get(0).getCompressPath());
                            Network.uploadFileForUrl(file, new HttpUtil.MyCallback() {
                                @Override
                                public void success(Response res) throws IOException {
                                    String resStr = res.body().string();
                                    ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                                    if (resultBean.getCode().equals(200)) {
                                        getActivity().runOnUiThread(() -> {
                                            mMiniLoadingDialog.dismiss();
                                            richEditor.insertImage(resultBean.getData(), "dachshund");
                                            KeyBoardUtils.openKeybord(editName, getContext());
                                            richEditor.postDelayed(new Runnable() {
                                                @Override
                                                public void run() {
                                                    if (richEditor != null) {
                                                        richEditor.scrollToBottom();
                                                    }
                                                }
                                            }, 200);
                                        });
                                    } else {
                                        failed(new IOException(resultBean.getMsg()));
                                    }
                                }

                                @Override
                                public void failed(IOException e) {
                                    getActivity().runOnUiThread(() -> {
                                        Utils.showToast(e.getMessage());
                                        mMiniLoadingDialog.dismiss();
                                        Utils.showToast("上传图片失败");
                                    });
                                }
                            });


                            //richEditor.insertImage("file://" + result.get(0).getCompressPath(), "dachshund");
//                            KeyBoardUtils.openKeybord(editName, getContext());
//                            richEditor.postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//                                    if (richEditor != null) {
//                                        richEditor.scrollToBottom();
//                                    }
//                                }
//                            }, 200);

                        }

                        @Override
                        public void onCancel() {
                            // 取消
                        }
                    });
        });

        richEditor.setOnClickListener(v -> againEdit());
    }

    public void publishTravel(int userId) {
        if (mViewModel.getItemTravelLiveData().getValue() == null) {
            return;
        }
        for(TravelItemBean item : mViewModel.getItemTravelLiveData().getValue()) {
//            if (Utils.isStringEmpty(item.getText())) {
//                Utils.showToast("请完成所有游记");
//                return;
//            }
            ArrayList<String> imgList = RichUtils.returnImageUrlsFromHtml(item.getText());
            Utils.Sout(imgList.toString());
        }

        if (Utils.isStringEmpty(mViewModel.getTravelTitleLiveData().getValue())) {
            Utils.showToast("标题不能为空");
            return;
        }

        HashMap<String, Object> mapBody = new HashMap<>();

        mapBody.put("user_id", userId);
        mapBody.put("team_id", mViewModel.getTeamIdLiveData().getValue());
        mapBody.put("travel_title", mViewModel.getTravelTitleLiveData().getValue());
        mapBody.put("travel_item", mViewModel.getItemTravelLiveData().getValue());

        String jsonBody = JsonUtilNew.mapToJson(mapBody);

        Network.publishTravel(jsonBody, new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                ResultBean<String> resultBean = JsonUtilNew
                        .fromJsonObject(res.body().string(), String.class);
                if (resultBean.getCode().equals(200)) {
                    getActivity().runOnUiThread(() -> {
                        Utils.showToast("发布成功");
                        popToBack();
                    });

                } else {
                    failed(new IOException(resultBean.getMsg()));
                }
            }

            @Override
            public void failed(IOException e) {
                Utils.showToastSync("发布失败");
                Utils.Sout(e.getMessage());
            }
        });
    }



    private void againEdit() {
        //如果第一次点击例如加粗，没有焦点时，获取焦点并弹出软键盘
        richEditor.focusEditor();
        KeyBoardUtils.openKeybord(editName, getContext());
    }

    private void initEditor() {

        richEditor.setEditorHeight(400);

        richEditor.getSettings().setAllowFileAccess(true);


        //输入框显示字体的大小
        richEditor.setEditorFontSize(16);

        //输入框显示字体的颜色
        richEditor.setEditorFontColor(getResources().getColor(R.color.black1b, null));
        //输入框背景设置
        richEditor.setEditorBackgroundColor(Color.WHITE);
        //输入框文本padding
        richEditor.setPadding(15, 10, 15, 10);
        //输入提示文本
        richEditor.setPlaceholder("请开始你的创作！~");


//        richEditor.setOnContentChangeListener(height -> {
//            Utils.Sout("contentChange height:" + height);
//            Utils.Sout("Scroll height:" + editTravelScroll.getHeight());
//        });

        //文本输入框监听事件
        richEditor.setOnTextChangeListener(new RichEditor.OnTextChangeListener() {

            @Override
            public void onTextChange(String text) {

//                editTravelScroll.post(() -> {
//                    editTravelScroll.fullScroll(View.FOCUS_DOWN);
//                });
//                richEditor.focusEditor();


                int selectPosition = tabLayout.getSelectedTabPosition();
                List<TravelItemBean> itemTravels = mViewModel.getItemTravelLiveData().getValue();
                String oldText = itemTravels.get(selectPosition).getText();
                if (!Utils.isStringEmpty(oldText) && text.length() > 100 && text.length() > oldText.length()) {
                    if (oldText.equals(text.substring(0, oldText.length()))) {
                        editTravelScroll.post(() -> editTravelScroll.fullScroll(View.FOCUS_DOWN));
                    }
                }

                Log.e("富文本文字变动", text);

                // 文本非空则记录到对应活动中去
                if (!Utils.isStringEmpty(text)) {
                    itemTravels.get(selectPosition).setText(text);
                    mViewModel.getItemTravelLiveData().setValue(itemTravels);
                } else if (text.equals(" ")) {
                    itemTravels.get(selectPosition).setText("");
                    mViewModel.getItemTravelLiveData().setValue(itemTravels);
                }



                if (TextUtils.isEmpty(editName.getText().toString().trim())) {
                    txtPublish.setSelected(false);
                    txtPublish.setEnabled(false);
                    txtPreview.setSelected(false);
                    txtPreview.setEnabled(false);
                    return;
                }

                if (TextUtils.isEmpty(text)) {
                    txtPublish.setSelected(false);
                    txtPublish.setEnabled(false);
                    txtPreview.setSelected(false);
                    txtPreview.setEnabled(false);
                } else {

                    if (TextUtils.isEmpty(Html.fromHtml(text))) {
                        txtPublish.setSelected(false);
                        txtPublish.setEnabled(false);
                        txtPreview.setSelected(false);
                        txtPreview.setEnabled(false);
                    } else {
                        txtPublish.setSelected(true);
                        txtPublish.setEnabled(true);
                        txtPreview.setSelected(true);
                        txtPreview.setEnabled(true);
                    }

                }

            }

        });

        editName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String html = richEditor.getHtml();

                mViewModel.getTravelTitleLiveData().setValue(s.toString());

                if (TextUtils.isEmpty(html)) {
                    txtPublish.setSelected(false);
                    txtPublish.setEnabled(false);
                    txtPreview.setSelected(false);
                    txtPreview.setEnabled(false);
                    return;
                } else {
                    if (TextUtils.isEmpty(Html.fromHtml(html))) {
                        txtPublish.setSelected(false);
                        txtPublish.setEnabled(false);
                        txtPreview.setSelected(false);
                        txtPreview.setEnabled(false);
                        return;
                    } else {
                        txtPublish.setSelected(true);
                        txtPublish.setEnabled(true);
                        txtPreview.setSelected(true);
                        txtPreview.setEnabled(true);
                    }
                }


                if (TextUtils.isEmpty(s.toString())) {
                    txtPublish.setSelected(false);
                    txtPublish.setEnabled(false);
                    txtPreview.setSelected(false);
                    txtPreview.setEnabled(false);
                } else {
                    txtPublish.setSelected(true);
                    txtPublish.setEnabled(true);
                    txtPreview.setSelected(true);
                    txtPreview.setEnabled(true);
                }


            }
        });

        richEditor.setOnDecorationChangeListener(new RichEditor.OnDecorationStateListener() {
            @Override
            public void onStateChangeListener(String text, List<RichEditor.Type> types) {
                ArrayList<String> flagArr = new ArrayList<>();
                for (int i = 0; i < types.size(); i++) {
                    flagArr.add(types.get(i).name());
                }

                if (flagArr.contains("H3")) {
                    buttonBold.setImageResource(R.mipmap.bold_);
                } else {
                    buttonBold.setImageResource(R.mipmap.bold);
                }

                if (flagArr.contains("UNDERLINE")) {
                    buttonUnderline.setImageResource(R.mipmap.underline_);
                } else {
                    buttonUnderline.setImageResource(R.mipmap.underline);
                }


                if (flagArr.contains("ORDEREDLIST")) {
                    buttonListUl.setImageResource(R.mipmap.list_ul);
                    buttonListOl.setImageResource(R.mipmap.list_ol_);
                } else {
                    buttonListOl.setImageResource(R.mipmap.list_ol);
                }

                if (flagArr.contains("UNORDEREDLIST")) {
                    buttonListOl.setImageResource(R.mipmap.list_ol);
                    buttonListUl.setImageResource(R.mipmap.list_ul_);
                } else {
                    buttonListUl.setImageResource(R.mipmap.list_ul);
                }

            }
        });


        richEditor.setImageClickListener(new RichEditor.ImageClickListener() {
            @Override
            public void onImageClick(String imageUrl) {
//                currentUrl = imageUrl;
//                popupWindow.showBottom(binding.getRoot(), 0.5f);
                //TODO: 图片点击事件
            }
        });



    }

    @Override
    public void onDestroy() {
        mMiniLoadingDialog.recycle();
        super.onDestroy();
    }
}